<template>
  <el-container>
    <el-aside>
      <el-container>
        <el-main>
          <el-tabs tab-position="top">
            <el-tab-pane label="执行操作" style="padding: 0px;">
              <template v-if="fun.length>0">
                <el-card shadow="never" v-for="(item,index) in fun" :key="index" >
                  <el-button style="width: 100%;height:100%;" type="primary" plain>
                    {{item.name}}
                  </el-button>
                </el-card>
              </template>
            </el-tab-pane>
            <el-tab-pane label="配置账号">
              <el-card shadow="never">
                <sc-form ref="userFormRef" :config="userConfig" v-model="userForm" :loading="loading">
                  <el-button type="primary">测试账户</el-button>
                </sc-form>
              </el-card>
            </el-tab-pane>
            <el-tab-pane label="配置参数" lazy>
              <el-card shadow="never">
                <sc-form @focus="handleFocus" ref="configFormRef" :config="config" v-model="configForm" :loading="loading">
                  <el-button type="primary" plain round>测试并预览</el-button>
                </sc-form>
              </el-card>
              <el-card shadow="never" header="获取测试数据" style="margin-top: 15px;">
                <sc-code-editor v-model="debug" mode="javascript" theme="darcula"></sc-code-editor>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-main>
        <el-footer></el-footer>
      </el-container>
    </el-aside>
    <el-container>
      <el-header>
        <el-button @click="run" type="primary" plain round>运行</el-button>
        <el-button type="primary" @click="visible = true" plain round>保存应用</el-button>
      </el-header>
      <el-main class="nopadding">
        <sc-code-editor style="height:100%" v-model="js" mode="javascript" theme="darcula"></sc-code-editor>
      </el-main>
      <el-footer>字符: {{js.length}}</el-footer>
    </el-container>
    <el-aside>
      <el-container>
        <el-header>运行日志</el-header>
        <el-main>2023-08-28 15:51:55.77665 +0800 CST m=+1638593.925287251 [ERROR] connection processDataFrame send response error: error=[disconnected]</el-main>
        <el-footer></el-footer>
      </el-container>
    </el-aside>
  </el-container>

  <div class="el-dialog__wrapper">
    <el-dialog custom-class="dialogClass" v-model="visible" style="width: 300px;z-index: 9999;"
      :modal="false"
      :close-on-click-modal="false"
    >
      <template v-slot:title>
        <span style="font-weight: 500; font-size: 14px;line-height: 24px;">变量设置</span>
      </template>
      <el-input type="text" v-model="varSearch" clearable></el-input>
      <el-tree style="margin-top: 15px;" :data="varGroup" ref="menu" :default-expand-all="true"  class="menu" node-key="id" highlight-current :expand-on-click-node="false" check-strictly @node-click="treeClick">
        <template #default="{node, data}">
          <span class="custom-tree-node">
            <span class="label">
              <component v-if="node.level==1" style="width: 12px;height: 12px;margin-top: 0px;" :is="'el-icon-position'">
              </component>
              {{ node.label }} <template v-if="data.value">( 
                <span style="color: rgba(0, 0, 0, 0.35);">
                {{ data.value }}
                </span>
              )</template>
            </span>
          </span>
        </template>
      </el-tree>
    </el-dialog>
</div>
</template>

<script>

  // import { parse } from 'comment-parser/lib';

  import parse from "@/utils/commentParser"

  import { defineAsyncComponent } from 'vue';
  const scCodeEditor = defineAsyncComponent(() => import('@/components/scCodeEditor'));

  export default {
    name: 'hiflow',
    components: {
      scCodeEditor
    },
    data() {
      return {
        curTarget:{},
        varGroup:[
          {
            label:'1.钉钉发送消息',
            value:'',
            children:[
              {
                label:'发送日期',
                value:'2021-01-01',
              }
            ]
          }
        ],
        varSearch:"",

        visible: false,
        gridData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        },],
        userForm:{},
        configForm:{},
        loading: false,
        config: {},
        form: {},
        fun:[],
        userConfig:{},
        debug:
`参数1: 9
参数2: 2
结果: 11`,
        js:

`$ = {
  env:[],
  var:[],
  input:{},
  output:{},
}

/**
 * @app 钉钉机器人 这里是简介
 * @icon 这里是图标
 * @type trigger 触发器
 * @author mradxz
 * @id cc.d4w.dingding
 * @version 1.0
 */

/**
 * @function sendMsg 发送钉钉消息
 * @param {number} userId 用户ID - 请输入用户ID
 * @param {number} [text=测试数据] 发送内容 - 请输入发送内容
 */
function sendMsg(userId,text) {
  return {
    userId,
    text
  };
}

/**
 * @function sendMsgMarkdown 发送markdown消息
 * @param {number} userId 用户ID - 请输入用户ID
 * @param {number} text 发送内容 - 请输入发送内容
 */
function sendMsgMarkdown(userId,text) {
  return {
    userId,
    text
  };
}

/**
 * @function test 测试账户
 * @param {string} username 用户名 - 请输入用户名
 * @param {number} password 密码 - 请输入密码
 */
function test(username,password) {
  
  return true;
}
`,
      }
    },
    methods: {
      handleFocus(e){
        this.curTarget = e.target;
        this.visible = true
      },
      treeClick(res){
        this.curTarget.value = this.curTarget.value + "${" + res.label + "}";
      },
      handleUser(){
        
        var parsed = parse(this.js)
        var config = [];

        parsed.forEach(meta=>{
          var tags = meta.tags
          if(tags[0].tag=='function' && tags[0].description=='测试账户') {
            config.push({
                label: tags[0].description,
                component: "title",
            })
            tags.forEach(item=>{
              if(item.tag == 'param'){
                var temp = item.description.split("-");
                var placeholder = temp.length>1?temp[1] :temp[0]
                config.push({
                  label: temp[0].trim(),
                  name: tags[0].name + "_" +item.name,
                  message: placeholder,
                  value: item['default'] || "",
                  component: "input",
                  options: {
                    placeholder: "",
                  },
                  rules: [
                    {required: true, message: placeholder, trigger: "blur"}
                  ],
                  requiredHandle: item.optional ? "$.required==true": "",
                })
              }
            });
          }

        })

        this.userConfig = {
          labelWidth: '80px',
          labelPosition: 'top',
          size: 'medium',
          formItems: config,
        };

      },
      run(){
        var _this = this;
        _this.fun = [];
        var parsed = parse(this.js)
        var config = [];

        parsed.forEach(meta=>{

          var tags = meta.tags

          if(tags[0].tag!='function' || tags[0].description=='测试账户') return;

          _this.fun.push({name:tags[0].description});

          config.push({
              label: tags[0].description,
              component: "title",
          })
          tags.forEach(item=>{
            if(item.tag == 'param'){

              var temp = item.description.split("-");
              var placeholder = temp.length>1?temp[1] :temp[0];
              const v = (item['default']||"").trim()
              config.push({
                label: temp[0].trim(),
                name: tags[0].name + "_" + item.name,
                message: placeholder,
                value: v,
                component: "input",
                options: {
                  placeholder: '',
                },
                rules: [
                  {required: true, message: placeholder, trigger: "blur"}
                ],
                requiredHandle: item.optional ? "$.required==true": "",
              })
            }
          });

        })

        this.config = {
          labelWidth: '80px',
          labelPosition: 'top',
          size: 'medium',
          formItems: config,
        };

      }
    },
    mounted() {
      this.run();
      this.handleUser();
    }
  }
</script>

<style type="text/css">
  

.el-dialog{
  pointer-events: auto;
}

</style>

<style lang="scss">
  .el-dialog__wrapper{
    pointer-events: none;
  }
  .dialogClass .el-dialog__body {
    padding-top:0px;
  }
  .dialogClass{
    margin-left:370px;
    margin-top:90px;
  }

</style>
